﻿using LiteFramework.Model;
using System;

namespace LiteFramework.Server
{
    [Serializable]
    public class FlowUser : IDisposable
    {
        private readonly ContextToken _originalToken = null;

        public readonly User OriginalUser = null;
        public readonly string OriginalPrimeTag = null;

        internal FlowUser()
        {
            _originalToken = ServerApplication.Current.GetSecurityToken();

            OriginalUser = ServerApplication.Current.TrueUser;
            OriginalPrimeTag = ServerApplication.PrimeTag;
        }

        public FlowUser(ContextToken flowToken)
            : this(flowToken, null)
        {
        }

        public FlowUser(ContextToken flowToken, string primeTag)
            : this()
        {
            ServerApplication.Current.SetSecurityToken(flowToken);

            if (primeTag != null)
                ServerApplication.Current.InitPrimeTag(primeTag);
        }

        public void Restore()
        {
            ServerApplication.Current.SetSecurityToken(_originalToken);
            ServerApplication.Current.InitPrimeTag(OriginalPrimeTag);
        }

        public void Dispose()
        {
            Restore();
        }
    }
}
